package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import org.json.JSONException;

public class ChangeHandleFragment extends Fragment implements OnClickListener {
  /** 执行人 */
  private static final int CHOOSE_RECIPIENT = 0;
  public static final String EXTRA_TASK_ID =
      "com.isunland.managesystem.ui.ChangeHandleFragment.EXTRA_TASK_ID";
  private BaseVolleyActivity mActivity;
  private CurrentUser mCurrentUser;

  private TextView mtvRecipient;//接收人
  private ImageView mibRecipient;//接收人
  private RadioGroup mrgAlertMessage;//接收人
  private CheckBox mcbAlertStation;//站内消息
  private CheckBox mcbAlertPhone;//手机消息
  private EditText metChangeCause;//转交原因
  private String recipientName = "";//接收人姓名
  private String recipientId = "";//接收人id
  private String type1 = "3";//消息提醒方式:站内
  private String type2 = "";//消息提醒方式:手机
  protected String mTaskId;

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);//显示菜单按钮
    if (NavUtils.getParentActivityName(getActivity()) != null) {
      ((BaseVolleyActivity) getActivity()).getSupportActionBar()
          .setDisplayHomeAsUpEnabled(true);//回退键
    }
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.changeHandle);
    mActivity = (BaseVolleyActivity) getActivity();
    mCurrentUser = CurrentUser.newInstance(getActivity());
    mTaskId = getActivity().getIntent().getStringExtra(EXTRA_TASK_ID);
    super.onCreate(savedInstanceState);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_confirm, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_change_handle, container, false);
    mtvRecipient = (TextView) v.findViewById(R.id.tv_recipient);//接收人
    mibRecipient = (ImageView) v.findViewById(R.id.ib_recipient);//接收人
    mrgAlertMessage = (RadioGroup) v.findViewById(R.id.rg_alert_message);//接收人
    mcbAlertStation = (CheckBox) v.findViewById(R.id.cb_alert_station);//站内消息
    mcbAlertPhone = (CheckBox) v.findViewById(R.id.cb_alert_phone);//手机消息
    metChangeCause = (EditText) v.findViewById(R.id.et_change_cause);//转交原因

    mibRecipient.setOnClickListener(this);
    //		mrgAlertMessage.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    //
    //			@Override
    //			public void onCheckedChanged(RadioGroup group, int checkedId) {
    //				switch (checkedId) {
    //				case R.id.cb_alert_station:
    //
    //					break;
    //
    //				case R.id.cb_alert_phone:
    //
    //					break;
    //
    //				default:
    //					break;
    //				}
    //
    //
    //			}
    //		});
    //站内消息
    mcbAlertStation.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

      @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        //如果被选中
        if (isChecked) {
          type1 = "3";
        } else {
          type1 = "";
        }
      }
    });
    //手机消息
    mcbAlertPhone.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

      @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        //如果被选中
        if (isChecked) {
          type2 = "2";
        } else {
          type2 = "";
        }
      }
    });

    return v;
  }

  @Override public void onClick(View arg0) {
    switch (arg0.getId()) {
      case R.id.ib_recipient:
        showDialog(CHOOSE_RECIPIENT);//选择接收人
        break;

      default:
        break;
    }
  }

  private void showDialog(int chooseRecipient) {
    Intent i = new Intent(getActivity(), AppointerListActivity.class);
    i.putExtra(AppointerListFragment.EXTRA_FROM, AppointerListFragment.VALUE_TO_DO);
    startActivityForResult(i, chooseRecipient);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }

        break;
      case R.id.menu_item_confirm:
        //判断转交办理人和原因是否为空
        if (TextUtils.isEmpty(mtvRecipient.getText().toString()) || TextUtils.isEmpty(
            metChangeCause.getText().toString())) {
          Toast.makeText(getActivity(), R.string.notComplete, Toast.LENGTH_SHORT).show();
        } else {
          //提交转办的人和转办原因
          volleChange();
        }

        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  //自定义提交转办的人和转办原因方法
  private void volleChange() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_CHANGE_HANDLE);

    HashMap<String, String> params = new HashMap<String, String>();

    params.put("taskId", mTaskId);
    params.put("assigneeId", recipientId);
    params.put("assigneeName", recipientName);
    params.put("memo", metChangeCause.getText().toString());
    //站内
    if (!"".equals(type1) && "".equals(type2)) {
      params.put("informtype", type1);
    }
    //消息
    if (!"".equals(type2) && "".equals(type1)) {
      params.put("informtype", type2);
    }
    //都选
    if (!"".equals(type1) && !"".equals(type2)) {
      StringBuffer sb = new StringBuffer();
      sb.append(type2).append(",").append(type1);
      params.put("informtype", sb.toString());
    }

    LogUtil.i("params===" + params.toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        LogUtil.i("转交arg0===" + arg0);
        MyUtils.dismissDialog();
        //解析
        SuccessMessage result = new Gson().fromJson(arg0, SuccessMessage.class);
        if (null == result || null == result.getResult()) {
          Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          return;
        }
        String successType = result.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          //						Toast.makeText(getActivity(),
          //								R.string.failure_operation, Toast.LENGTH_SHORT)
          //								.show();
          ToastUtil.show(result.getMessage());
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();

          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == CHOOSE_RECIPIENT) {
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);

      recipientName = customer.getName();// 执行人姓名
      recipientId = customer.getId();// 执行人工号
      mtvRecipient.setText(recipientName);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  public static ChangeHandleFragment newInstance(String taskId) {
    Bundle args = new Bundle();
    args.putString(EXTRA_TASK_ID, taskId);

    ChangeHandleFragment fragment = new ChangeHandleFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
